﻿'use strict';
angular.module('csModule', ['ngTable'])
.factory('csTable', ['$filter', '$timeout', 'ngTableParams', function ($filter, $timeout, ngTableParams) {
    var table = {};

    table.table = function (parameters, settings, d) {
        var externalFilterName = 'external_filter_name_static';
        var data = d;
        var defaultParameters = {
            isPage: true,
            page: 1,            // show first page
            count: 25,          // count per page
        };

        var defaultSettings = {
            //getData: function ($defer, params) {
            //    //var filters = params.filter();
            //    var filters = params.filter();
            //    //var filter = params.$params.filter;
            //    var orderedData = data;

            //    //其他过滤
            //    orderedData = filters ? $filter('filter')(orderedData, filters) : orderedData;
            //    //orderedData = filter ? $filter('filter')(orderedData, filter) : orderedData;

            //    //排序
            //    orderedData = params.sorting() ? $filter('orderBy')(orderedData, params.orderBy()) : orderedData;

            //    params.total(orderedData.length);
            //    if (parameters.isPage) {
            //        orderedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
            //    }
            //    $defer.resolve(orderedData);
            //}
            dataset: data,
        };
        angular.extend(defaultParameters, parameters);
        angular.extend(defaultSettings, settings);
        if (!defaultParameters.isPage) {
            defaultSettings.counts = [];
            defaultParameters.count = data.length;
        }

        //限定全局filter $ ，指定参与filter的字段
        var hasOrFilter = defaultSettings.orFilter && defaultSettings.orFilter.fields && defaultSettings.orFilter.fields.length > 1;
        var hasExternalFilter = angular.isFunction(defaultSettings.externalFilter);
        if (hasOrFilter || hasExternalFilter) {
            defaultSettings.filterOptions = defaultSettings.filterOptions || {};
            defaultSettings.filterOptions.filterFn = function (data, filterValues, comparator) {
                return data.filter(function (item) {
                    var copyFilterValues = angular.copy(filterValues);
                    delete copyFilterValues[externalFilterName];
                    var result = false;
                    var tableSettings = tableParams.settings();
                    var arr = $filter('filter')([item], copyFilterValues, comparator);
                    if (arr && arr.length == 1) {
                        if (copyFilterValues.$ && copyFilterValues.$ != '' && hasOrFilter) {
                            for (var i = 0; i < tableSettings.orFilter.fields.length; i++) {
                                var field = tableSettings.orFilter.fields[i];
                                var filter = {};
                                filter[field] = copyFilterValues.$;
                                var orArr = $filter('filter')([item], filter, comparator);
                                if (orArr && orArr.length == 1) {
                                    result = true;
                                }
                            }
                        } else {
                            result = true;
                        }

                        if (result && hasExternalFilter) {
                            result = defaultSettings.externalFilter(item);
                        }
                    }
                    return result;
                });
            };

        }

        var tableParams = new ngTableParams(defaultParameters, defaultSettings);
        if (!defaultParameters.isPage) {
            var timer = $timeout(function () {
                $('.ng-table-pager').hide();
                $timeout.cancel(timer);
            });
        }



        tableParams.setData = function (d) {
            data = d;
            tableParams.settings().dataset = data;
            if (!defaultParameters.isPage) {
                tableParams.parameters({
                    'count': data.length
                })
            }
        };
        tableParams.orFilter = function (a) {
            return settings.orFilter;
        };
        var changeIndex = 1;
        tableParams.filterChange = function () {
            if (hasExternalFilter) {
                tableParams.filter()[externalFilterName] = changeIndex++;
            }
        };
        return tableParams;
    };

    return table;
}]).run(['$templateCache', function ($templateCache) {
    $templateCache.put('ng-table/pager.html', '<div class="ng-cloak ng-table-pager" ng-if="params.data.length"><div ng-if="params.settings().counts.length" class="ng-table-counts btn-group pull-right"> <button ng-repeat="count in params.settings().counts" type="button" ng-class="{\'active\':params.count()==count}" ng-click="params.count(count)" class="btn btn-default"> <span ng-bind="count"></span> </button> </div> <ul ng-if="pages.length" style="margin-top:0px;" class="pagination ng-table-pagination"> <li ng-class="{\'disabled\': !page.active && !page.current, \'active\': page.current}" ng-repeat="page in pages" ng-switch="page.type"> <a ng-switch-when="prev" ng-click="params.page(page.number)" href="">&laquo;</a> <a ng-switch-when="first" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="page" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="more" ng-click="params.page(page.number)" href="">&#8230;</a> <a ng-switch-when="last" ng-click="params.page(page.number)" href=""><span ng-bind="page.number"></span></a> <a ng-switch-when="next" ng-click="params.page(page.number)" href="">&raquo;</a> </li> </ul><div style="margin-right:20px;" class="pull-left btn btn-default">总数：<span class="badge">{{params.total()}}</span></div>  </div> ');
}])
.factory('dataSource', ['$filter', '$q', function ($filter, $q) {
    /*
        读取外部数据源，暂无缓存功能
    */
    var source = function (rootSettings) {
        var settings = rootSettings;
        var caches = {};
        var parameterCaches = {};
        var getFromServer = function (parameter, deferred) {
            settings.post(['system', 'datasource', 'GetListView'], parameter, function (data) {
                deferred.resolve(data);
            });
        };
        ///获取外部数据源
        this.get = function (code, view, parameters) {
            var deferred = $q.defer();
            var parameter = { Code: code, View: view, Parameters: parameters };
            getFromServer(parameter, deferred);
            return deferred.promise;
        };
        //获取参数
        this.getParameter = function (code) {
            var deferred = $q.defer();
            if (parameterCaches[code]) {
                var data = parameterCaches[code];
                deferred.resolve(data);
            }
            else {
                settings.post(['system', 'parameter', 'GetByClassCode'], code, function (data) {
                    deferred.resolve(data);
                });
            }
            return deferred.promise;
        };
    };
    return source;
}])
.filter('csdate', ['$filter', function ($filter) {
    return function (input, format) {
        if (input) {
            return $filter('date')(moment(input).toDate(), format ? format : "yyyy-MM-dd");
        } else {
            return '';
        }
    };
}])
.filter('cstime', ['$filter', function ($filter) {
    return function (input, format) {
        if (input) {
            return $filter('date')(moment(input).toDate(), format ? format : "yyyy-MM-dd HH:mm");
        } else {
            return '';
        }
    };
}])
.factory('periodUtil', ['$filter', '$q', function ($filter, $q) {
    var periodUtil = {
        get: function (date) {
            return date.getFullYear().toString() + (date.getMonth() > 8 ? '' : '0') + (date.getMonth() + 1).toString();
        },
        add: function (period, add) {
            var periodDate = new Date(parseInt(period.substring(0, 4)), parseInt(period.substring(4, 6)) - 1, 1);
            return periodUtil.get(new Date(periodDate.getFullYear(), periodDate.getMonth() + add, periodDate.getDate()));
        },
        duration: function (startPeriod, endPeriod) {
            var startPeriodDate = new Date(parseInt(startPeriod.substring(0, 4)), parseInt(startPeriod.substring(4, 6)) - 1, 1);
            var endPeriodDate = new Date(parseInt(endPeriod.substring(0, 4)), parseInt(endPeriod.substring(4, 6)) - 1, 1);
            var periods = [];
            while (endPeriodDate >= startPeriodDate) {
                var str = startPeriodDate.getFullYear().toString() + (startPeriodDate.getMonth() > 8 ? '' : '0') + (startPeriodDate.getMonth() + 1).toString();
                periods.push(str);
                startPeriodDate = new Date(startPeriodDate.getFullYear(), startPeriodDate.getMonth() + 1, 1);
            }
            return periods;
        }
    };
    return periodUtil;
}])
.factory('api', ['$http', '$filter', '$timeout', '$location', function ($http, $filter, $timeout, $location) {
    var getApiUrl = function (module, name, action) {
        return '/api.ashx?app=anonymous&name=' + module + '&ctrl=' + name + '&action=' + action;
    };
    var showError = function (msg) {
        toastr.options = {
            closeButton: true,
            debug: false,
            positionClass: 'toast-top-right',
            onclick: null
        };
        toastr.error(msg);
    };
    var showSuccess = function (msg) {
        toastr.options = {
            closeButton: true,
            debug: false,
            positionClass: 'toast-top-right',
            onclick: null
        };
        toastr.success(msg);
    };
    var invoke = function (option, input) {
        var url = getApiUrl(option.module, option.name, option.action);
        $http.post(url, input).success(
        function (result, status, headers, config) {
            console.log("http post success. url:" + url + "| status:" + status + "| args:" + $filter("json")(input));
            if (result && result.Status && result.Status < 0) {
                if (result.Status < 0) { //< 0代表错误 
                    if (option.error) {
                        option.error(result, result.Status);
                    }
                    if (result.Message) {
                        showError(result.Message);
                    }
                }
            } else {
                if (result && result.Status && result.Status > 0 && result.Message) {
                    showSuccess(result.Message);
                    if (option.success) {
                        option.success(result, result.Status, headers, config);
                    }
                    if (option.successUrl) {
                        $location.path(option.successUrl);
                    }
                    if (option.successAbsulateUrl) {                        
                        $timeout(function () {
                            location.href = option.successAbsulateUrl;
                        }, 2000);
                    }                    
                }
                else {
                    if (option.successText) {
                        showSuccess(option.successText);
                    }
                    if (option.success) {
                        option.success(result, status, headers, config);
                    }
                    if (option.successUrl) {
                        $location.path(option.successUrl);
                    }
                    if (option.successAbsulateUrl) {
                        $timeout(function () {
                            location.href = option.successAbsulateUrl;
                        }, 2000);
                    }
                }
            }
        }).error(function (result, status, headers, config) {
            if (result) {
                showError("系统错误，请联系管理员");
            }
            if (option.error) {
                option.error(result, status, headers, config);
            }

        });
    };
    var api = {
        defaultOption: { module: '', name: '' },
        Invoke: function (input,option) {
            if (!option) option = {};
            option.module = option.module ? option.module : this.defaultOption.module;
            option.name = option.name ? option.name : this.defaultOption.name;
            option.action = option.action ? option.action : this.defaultOption.action;
            invoke(option, input);
        },
        Save: function (input, option) {
            if (!option) option = {};
            option.module = option.module ? option.module : this.defaultOption.module;
            option.name = option.name ? option.name : this.defaultOption.name;
            option.action = option.action ? option.action : "Save";
            option.successText = option.successText ? option.successText : "保存成功";
            invoke(option, input);
        },
        Delete: function (input, success, error, successText, errorText) {
            if (!option) option = {};
            option.module = option.module ? option.module : this.defaultOption.module;
            option.name = option.name ? option.name : this.defaultOption.name;
            option.action = option.action ? option.action : "Delete";
            option.successText = option.successText ? option.successText : "删除成功";
            invoke(option, input);
        }
    };
    return api;
}]);